<?

if (isset($_SERVER['SERVER_NAME'])) {
	echo "run this script in a command line\n";
	exit(0);
}

$base = dirname(__FILE__);
$url = 'http://closure-compiler.appspot.com/compile';
$src = $base . '/../sources/js';
$themes = $base . '/../sources/css/themes';
$out_themes = $base . '/../release/themes';
$out = $base . '/../release/jquery.ys.js';
$out_min = $base . '/../release/jquery.ys.min.js';
$ver = $base . '/../VERSION';
$hdr = 
'/*
	Copyright (c) 2011 Andrey O. Zbitnev (azbitnev@gmail.com)
	Licensed under the MIT License (LICENSE.txt).

	Project home: http://code.google.com/p/yellow-submarine/

	Version: ' . file_get_contents($ver) . '
*/
';

$source = file_get_contents("$src/ys.core.js");
foreach (scandir($src) as $file) {
	if (preg_match('/\.js$/', $file) && $file != 'ys.core.js')
		$source .= file_get_contents("$src/$file");
}

file_put_contents($out, $source);

$params = array(
	'js_code' => $source,
	'compilation_level' => 'SIMPLE_OPTIMIZATIONS',
	'output_format' => 'json',
	'output_info' => array('compiled_code', 'warnings', 'errors', 'statistics'),
);

$curl_opts = array(
	CURLOPT_POST => true,
	CURLOPT_POSTFIELDS => preg_replace('/\%5B\d+\%5D=/', '=', http_build_query($params)),
	CURLOPT_RETURNTRANSFER => true,
	CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
	CURLOPT_FOLLOWLOCATION => true,
	CURLOPT_FRESH_CONNECT => true,
	CURLOPT_HTTPHEADER => array(
		"Expect:",
	),

	//CURLOPT_VERBOSE => true,
);

echo "INFO Compiling JavaScript\n";

$ch = curl_init($url);
curl_setopt_array($ch, $curl_opts);
$response = curl_exec($ch);
curl_close($ch);

$response = @json_decode($response, true);

if (count(@$response['errors'])) foreach ($response['errors'] as $msg)
	echo "ERROR at line {$msg['lineno']}: {$msg['error']}\n----------------------------------------------\n{$msg['line']}\n----------------------------------------------\n";

if (count(@$response['warnings'])) foreach ($response['warning'] as $msg)
	echo "WARNING at line {$msg['lineno']}: {$msg['warning']}\n----------------------------------------------\n{$msg['line']}\n----------------------------------------------\n";

if (isset($response['compiledCode'])) {
	file_put_contents($out_min, $hdr . $response['compiledCode']);
	echo "DONE original size = {$response['statistics']['originalSize']}, release size = {$response['statistics']['compressedSize']}\n";
}

class css_packer {

	protected static function replacement($m) {
		$h = preg_replace('/[\s\r\n\t]+/m', ' ', trim($m[1]));
		$h = preg_replace('/\s*([:;])\s*/', '$1', $h);
		$h = preg_replace('/;$/', '', $h);
		$h = preg_replace('/:0(em|px|pt)$/', ':0', $h);
		return '{' . $h . '}';
	}

	public static function optimize($css) {
		$s = array();
		foreach (explode("\n", $css) as $line) {
			$m = array();
			if (preg_match('/^([^\{]+)\{([^\}]+)\}$/', $line, $m)) {
				$selector = trim($m[1]);
				$rules = $m[2];
				if (!isset($s[$selector]))
					$s[$selector] = '';
				$s[$selector] .= ($s[$selector] == '' || preg_match('/\;$/', $s[$selector]) ? '' : ';') . $rules;
			}
		}
		$css = '';
		foreach ($s as $selector => $rules)
			$css .= $selector . ' {' . $rules . "}\n";
		return $css;
	}

	public static function pack($css, $keep_comments = true) {
		$css = preg_replace_callback('/\{((?:[^\}]|[\s\t\r\n])*)\}/m', array('css_packer', 'replacement'), $css);
		if (!$keep_comments)
			$css = preg_replace('/\/\*((?:.|[\s\t\r\n])*?)\*\//m', '', $css);
		$css = preg_replace('/[\r\n]+/', "\n", $css);
		return trim($css);
	}
}

function mkdataurl($m) {
	global $path;
	if (preg_match('/^\'?data\:/', $m[1]))
		return $m[0];
	$file = str_replace("\\", '/', "$path/{$m[1]}");
	return "url(data:image/png;base64," . base64_encode(file_get_contents($file)) . ")";
}

global $path;
foreach (scandir($themes) as $theme) {
	$path = "$themes/$theme";
	if (!preg_match('/^\./', $theme) && is_dir($path)) {
		echo "INFO Compiling CSS theme \"$theme\"\n";
		$source = '';
		foreach (scandir($path) as $file) {
			if (preg_match('/\.css$/', $file))
				$source .= file_get_contents("$path/$file");
		}
		$osize = strlen($source);
		//$source = $hdr . css_packer::optimize(css_packer::pack($source, false));
		$source = $hdr . css_packer::pack($source, false);
		$source = preg_replace_callback('/url\(([^)]+)\)/', 'mkdataurl', preg_replace('/\t/', '', preg_replace('/\/\*.*\*\//', '', $source)));
		file_put_contents("$out_themes/{$theme}.min.css", $source);
		echo "DONE original size = $osize, release size = " . strlen($source) . "\n";
	}
}

?>